package com.xyyl.patient.core.filter;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * @projectName:xyyl-oms-core
 * @ClassName: SQLFilter
 * @Description: SQL过滤
 * @author chens
 * @date 2017年9月12日
 *
 */
public class SQLFilter {

	private static Logger logger = LogManager.getLogger(SQLFilter.class);

	/**
	 * SQL注入过滤
	 * 
	 * @param str
	 *            待验证的字符串
	 */
	public static String sqlInject(String str) {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		// 去掉'|"|;|\字符
		str = StringUtils.replace(str, "'", "");
		str = StringUtils.replace(str, "\"", "");
		str = StringUtils.replace(str, ";", "");
		str = StringUtils.replace(str, "\\", "");

		// 转换成小写
		str = str.toLowerCase();

		// 非法字符
		String[] keywords = { "master", "truncate", "insert", "select", "delete", "update", "declare", "alert",
				"create", "drop" };

		// 判断是否包含非法字符
		for (String keyword : keywords) {
			if (str.indexOf(keyword) != -1 || str.equals(keyword)) {
				try {
					throw new Exception("Contain illegal characters '" + str + "'");
				} catch (Exception e) {
					logger.error(e);
					return null;
				}
			}
		}

		return str;
	}
}
